package com.photoeditor.demo.model.subscribe.manager;

import android.content.Context;
import android.content.res.Resources;
import android.support.v4.os.ConfigurationCompat;
import android.support.v4.os.LocaleListCompat;
import android.text.TextUtils;

import com.common.base.utils.SystemUtils;
import com.common.base.utils.thread.ThreadPool;

import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;

import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;

import static com.photoeditor.demo.statistics.StatisticsConstant.EVENT_ACTION_BTN_CLICK;
import static com.photoeditor.demo.statistics.StatisticsConstant.EVENT_ACTION_CLOSE;
import static com.photoeditor.demo.statistics.StatisticsConstant.EVENT_ACTION_FAIL;
import static com.photoeditor.demo.statistics.StatisticsConstant.EVENT_ACTION_SHOW;
import static com.photoeditor.demo.statistics.StatisticsConstant.EVENT_ACTION_SUCC;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_ENTRANCE;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_MAIN_PAGE_TYPE;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_SUB_FAIL_REASON;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_SUB_PACK;

/**
 * Created by Lai on 2018/11/29 0029.
 */
public class VipStatisticUtil  {

    private IVipStatistic mVipStatistic;

    private String mClickStatistic;

    private long mLastLeaveTime;

    //拿不到渠道的统计先缓存下来，回调时上传
    private static CopyOnWriteArrayList<String> mCacheStatistic;

    public VipStatisticUtil(IVipStatistic vipStatistic) {
        mVipStatistic = vipStatistic;
//        AppApplication.getApplication().addBuyUserListener(this);
    }

    private void cacheOrStatistic(String statistic) {
//        String mediaSource = BuyUserManager.getInstance().getBuyUserSource();
//        if (TextUtils.equals(mediaSource, BuyUserManager.BUY_USER_UNKNOWN)) {
//            if (mCacheStatistic == null) {
//                mCacheStatistic = new CopyOnWriteArrayList<>();
//            }
//            mCacheStatistic.add(statistic);
//        } else {
//            StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
//                    , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
//                    , statistic + getKeySuffix());
//        }
    }

    private synchronized void statisticCache() {
        ThreadPool.runOnNonUIThread(new Runnable() {
            @Override
            public void run() {
                if (mCacheStatistic != null && !mCacheStatistic.isEmpty()) {
                    for (String next : mCacheStatistic) {
                        StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
                                , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
                                , next + getKeySuffix());
                    }
                    mCacheStatistic.clear();
                }
            }
        });
    }

    /**
     * 页面展示
     */
    public void statisticShow(boolean isRetainDialog) {
        cacheOrStatistic(mVipStatistic.getStatisticPageStr()
                + StatisticsConstant.STATISTIC_UNDERLINE
                + mVipStatistic.getStatisticEntranceStr()
                + StatisticsConstant.STATISTIC_UNDERLINE
                + StatisticsConstant.STATISTIC_EVENT_VALUE_SHOW_NEW);

//        if (mVipStatistic.statisticSubPageShowAndClick()) {
//            StatisticsUtils.statisticsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_VIP_SHOW);
//        }
        if (TextUtils.isEmpty(mVipStatistic.getSubscribeTypeStr())) {
            StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_SHOW,
                    KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr());
        } else {
            if(isRetainDialog){
                StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_SHOW,
                        KEY_MAIN_PAGE_TYPE, mVipStatistic.getSubscribeTypeStr());
            }else{
                StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_SHOW,
                        KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr(), KEY_MAIN_PAGE_TYPE, mVipStatistic.getSubscribeTypeStr());
            }

        }

    }

    /**
     * 页面点击
     *
     * @param clickStatistic
     */
    public void statisticClick(String sku,String clickStatistic,boolean isRetainDialog) {
        mClickStatistic = clickStatistic;
        cacheOrStatistic(mVipStatistic.getStatisticPageStr()
                + StatisticsConstant.STATISTIC_UNDERLINE
                + mVipStatistic.getStatisticEntranceStr()
                + StatisticsConstant.STATISTIC_UNDERLINE
                + clickStatistic);

//        if (mVipStatistic.statisticSubPageShowAndClick()) {
//            StatisticsUtils.statisticsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_VIP_CLICK);
//        }

        if (TextUtils.isEmpty(mVipStatistic.getSubscribeTypeStr())) {
            StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_BTN_CLICK,
                    KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr(), KEY_SUB_PACK, clickStatistic,
                    StatisticsConstant.KEY_SKU,sku);
        } else {
            if(isRetainDialog){
                StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_BTN_CLICK,
                        KEY_SUB_PACK, clickStatistic,
                        KEY_MAIN_PAGE_TYPE, mVipStatistic.getSubscribeTypeStr(),
                        StatisticsConstant.KEY_SKU,sku);
            }else{
                StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_BTN_CLICK,
                        KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr(), KEY_SUB_PACK, clickStatistic,
                        KEY_MAIN_PAGE_TYPE, mVipStatistic.getSubscribeTypeStr(),
                        StatisticsConstant.KEY_SKU,sku);
            }

        }

    }

    /**
     * 页面退出统计
     */
    public void statisticExit(boolean isRetainDialog) {
        StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
                , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
                , mVipStatistic.getStatisticPageStr()
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + mVipStatistic.getStatisticEntranceStr()
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + StatisticsConstant.STATISTIC_EVENT_VALUE_QUIT
                        + getKeySuffix());

        if (TextUtils.isEmpty(mVipStatistic.getSubscribeTypeStr())) {
            StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_CLOSE,
                    KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr());
        } else {
            if(isRetainDialog){
                //挽留弹窗只统计两个，不需要入口
                StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_CLOSE,
                        KEY_MAIN_PAGE_TYPE, mVipStatistic.getSubscribeTypeStr());
            }else{
                StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_CLOSE,
                        KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr(),
                        KEY_MAIN_PAGE_TYPE, mVipStatistic.getSubscribeTypeStr());
            }

        }

    }

    /**
     * 主页退出点击统计
     */
    public void statisticCloseClick() {
        StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
                , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
                , mVipStatistic.getStatisticPageStr()
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + mVipStatistic.getStatisticEntranceStr()
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + StatisticsConstant.STATISTIC_EVENT_VALUE_CLOSE_CLICK
                        + getKeySuffix());
    }

    /**
     * 购买成功
     *
     * @param sku
     */
    public void statisticSuccess(String sku,String entranceFunctions) {

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SUCC_VIPFUNSUB,
                StatisticsConstant.KEY_ENTRANCE, entranceFunctions,
                StatisticsConstant.KEY_SKU, sku);

        StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
                , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
                , mVipStatistic.getStatisticPageStr()
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + mVipStatistic.getStatisticEntranceStr()
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + getSkuType(sku)
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_BUY_SUCCESS_NEW
                        + getKeySuffix());

        if (TextUtils.isEmpty(mVipStatistic.getSubscribeTypeStr())) {
            StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_SUCC,
                    KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr(), KEY_SUB_PACK, getSkuType(sku),
                    StatisticsConstant.KEY_SKU,sku);
        } else {
            StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_SUCC,
                    KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr(), KEY_SUB_PACK, getSkuType(sku),
                    KEY_MAIN_PAGE_TYPE, mVipStatistic.getSubscribeTypeStr(),
                    StatisticsConstant.KEY_SKU,sku);
        }

    }

    /**
     * 购买失败
     *
     * @param resultCode
     */
    public void statisticFail(String sku,int resultCode,String type,String entranceFunctions) {
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FAIL_VIPFUNSUB,
                StatisticsConstant.KEY_ENTRANCE, entranceFunctions,
                StatisticsConstant.KEY_SKU, sku,
                KEY_SUB_FAIL_REASON, resultCode + "");

        cacheOrStatistic(mVipStatistic.getStatisticPageStr()
                + StatisticsConstant.STATISTIC_UNDERLINE
                + mVipStatistic.getStatisticEntranceStr()
                + StatisticsConstant.STATISTIC_UNDERLINE
                + mClickStatistic
                + StatisticsConstant.STATISTIC_UNDERLINE
                + StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_BUY_FAIL_NEW
                + resultCode);

        if (TextUtils.isEmpty(mVipStatistic.getSubscribeTypeStr())) {
            StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_FAIL,
                    KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr(), KEY_SUB_FAIL_REASON, resultCode + "",
                    KEY_SUB_PACK, type,
                    StatisticsConstant.KEY_SKU,sku);
        } else {
            StatisticsUtils.statisticGrowingIo(mVipStatistic.getStatisticPageStr() + EVENT_ACTION_FAIL,
                    KEY_ENTRANCE, mVipStatistic.getStatisticEntranceStr(), KEY_SUB_FAIL_REASON, resultCode + "",
                    KEY_SUB_PACK, type,
                    KEY_MAIN_PAGE_TYPE, mVipStatistic.getSubscribeTypeStr(),
                    StatisticsConstant.KEY_SKU,sku);
        }

    }

    /**
     * 退到后台
     */
    public void statisticLeave() {
        long time = System.currentTimeMillis();
        if (time - mLastLeaveTime <= 300) {
            return;
        }
        mLastLeaveTime = time;
        cacheOrStatistic(mVipStatistic.getStatisticPageStr()
                + StatisticsConstant.STATISTIC_UNDERLINE
                + mVipStatistic.getStatisticEntranceStr()
                + StatisticsConstant.STATISTIC_UNDERLINE
                + StatisticsConstant.STATISTIC_EVENT_VALUE_LEAVE);
    }

    /**
     * 视频播放时长
     *
     * @param time
     */
    public void statisticVideoTime(String time) {
        StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
                , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
                , mVipStatistic.getStatisticPageStr()
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + mVipStatistic.getStatisticEntranceStr()
                        + StatisticsConstant.STATISTIC_UNDERLINE
                        + StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_VIDEO
                        + time
                        + getKeySuffix());
    }

    /**
     * 没有安装或启动google
     */
    public static void statisticGoogleError() {
        statistic(StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_GOOGLE_ERROR
                + StatisticsConstant.STATISTIC_UNDERLINE
                + StatisticsConstant.STATISTIC_EVENT_VALUE_SHOW_NEW);
    }

    /**
     * 在首次展示订阅页面后未进入首页即退出应用，在当天再次进入应用的用户
     */
    public static void statisticLeaveIn() {
        statistic(StatisticsConstant.STATISTIC_EVENT_VIP_VALUE_REOPEN);
    }

    /**
     * 在使用的第一个高级功能订阅的用户（多次使用同个功能算一个）
     */
    public static void statisticFeatureSub(int usedFeaCount, String featureAlias) {
        String count = "";
        switch (usedFeaCount) {
            case 1:
                count = "1st";
                break;
            case 2:
                count = "2nd";
                break;
            case 3:
                count = "3th";
                break;
            case 4:
                count = "4th";
                break;
            case 5:
                count = "5th";
                break;
        }
        statistic("buy" + count + "fea_" + featureAlias);
    }

    public static void statistic(String... value) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < value.length; i++) {
            if (i != 0) {
                stringBuilder.append(StatisticsConstant.STATISTIC_UNDERLINE);
            }
            stringBuilder.append(value[i]);
        }
        StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
                , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
                , stringBuilder.toString()
                        + getKeySuffix());
    }

    public static void statistic(String value) {
        StatisticsUtils.statisticsCustomFunction(StatisticsConstant.STATISTIC_EVENT_FUNC_VIP
                , StatisticsConstant.STATISTIC_EVENT_KEY_VIP_NEW
                , value
                        + getKeySuffix());
    }

    public void onDestroy() {
//        AppApplication.getApplication().removeBuyUserListener(this);
        statisticCache();
    }

    public static String getSkuType(String sku) {
        String statistic = "unknown";
        if (TextUtils.equals(sku, SkuManager.getSkuInfoLast(SkuManager.TYPE_YEARLY))) {
            statistic = StatisticsConstant.SUB_PACK_VALUE_ANNUAL;
        } else if (TextUtils.equals(sku, SkuManager.getSkuInfoLast(SkuManager.TYPE_MONTHLY))) {
            statistic = StatisticsConstant.SUB_PACK_VALUE_MONTHLY;
        }
        return statistic;
    }

    public static String getKeySuffix() {
        return "";
//        return StatisticsConstant.STATISTIC_UNDERLINE + AppUtils.getVersionName(ComponentContext.getContext())
//                + StatisticsConstant.STATISTIC_UNDERLINE + getCountry(ComponentContext.getContext())
//                + StatisticsConstant.STATISTIC_UNDERLINE + BuyUserManager.getInstance().getBuyUserSource();
    }

    public static String getCountry(Context context) {
        String country = SystemUtils.getSimCountry(context);
        if (TextUtils.isEmpty(country)) {
            LocaleListCompat locales = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration());
            if (!locales.isEmpty()) {
                Locale locale = locales.get(0);
                if (locale != null) {
                    country = locale.getCountry();
                }
            }
        }
        return country;
    }

//    @Override
//    public void setBuyUser(String s, int i) {
//        statisticCache();
//    }

    public interface IVipStatistic {

        String getStatisticPageStr();

        String getStatisticEntranceStr();

        String getSubscribeTypeStr();

        boolean statisticSubPageShowAndClick();

        boolean isPageShowing();

    }

}
